<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\finance;


use app\common\model\finance\TransactionRecord;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * transaction逻辑
 * Class TransactionRecordLogic
 * @package app\adminapi\logic\finance
 */
class TransactionRecordLogic extends BaseLogic
{


    /**
     * @notes 添加transaction
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/08 19:39
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            TransactionRecord::create([
                'transaction_id' => $params['transaction_id'],
                'user_id' => $params['user_id'],
                'group_id' => $params['group_id'],
                'card_id' => $params['card_id'],
                'card_nickname' => $params['card_nickname'],
                'masked_card_number' => $params['masked_card_number'],
                'digital_wallet_token_id' => $params['digital_wallet_token_id'],
                'transaction_amount' => $params['transaction_amount'],
                'transaction_currency' => $params['transaction_currency'],
                'billing_amount' => $params['billing_amount'],
                'billing_currency' => $params['billing_currency'],
                'status' => $params['status'],
                'transaction_type' => $params['transaction_type'],
                'merchant_name' => $params['merchant_name'],
                'merchant_city' => $params['merchant_city'],
                'merchant_country' => $params['merchant_country'],
                'merchant_category' => $params['merchant_category'],
                'auth_code' => $params['auth_code'],
                'acquiring_institution_identifier' => $params['acquiring_institution_identifier'],
                'risk_actions_performed' => $params['risk_actions_performed'],
                'risk_factors' => $params['risk_factors'],
                'three_dsecure_outcome' => $params['three_dsecure_outcome'],
                'failure_reason' => $params['failure_reason'],
                'network_transaction_id' => $params['network_transaction_id'],
                'retrieval_ref' => $params['retrieval_ref'],
                'client_data' => $params['client_data'],
                'matched_authorizations' => $params['matched_authorizations'],
                'transaction_date' => $params['transaction_date'],
                'posted_date' => $params['posted_date']
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑transaction
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/08 19:39
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            TransactionRecord::where('id', $params['id'])->update([
                'transaction_id' => $params['transaction_id'],
                'user_id' => $params['user_id'],
                'group_id' => $params['group_id'],
                'card_id' => $params['card_id'],
                'card_nickname' => $params['card_nickname'],
                'masked_card_number' => $params['masked_card_number'],
                'digital_wallet_token_id' => $params['digital_wallet_token_id'],
                'transaction_amount' => $params['transaction_amount'],
                'transaction_currency' => $params['transaction_currency'],
                'billing_amount' => $params['billing_amount'],
                'billing_currency' => $params['billing_currency'],
                'status' => $params['status'],
                'transaction_type' => $params['transaction_type'],
                'merchant_name' => $params['merchant_name'],
                'merchant_city' => $params['merchant_city'],
                'merchant_country' => $params['merchant_country'],
                'merchant_category' => $params['merchant_category'],
                'auth_code' => $params['auth_code'],
                'acquiring_institution_identifier' => $params['acquiring_institution_identifier'],
                'risk_actions_performed' => $params['risk_actions_performed'],
                'risk_factors' => $params['risk_factors'],
                'three_dsecure_outcome' => $params['three_dsecure_outcome'],
                'failure_reason' => $params['failure_reason'],
                'network_transaction_id' => $params['network_transaction_id'],
                'retrieval_ref' => $params['retrieval_ref'],
                'client_data' => $params['client_data'],
                'matched_authorizations' => $params['matched_authorizations'],
                'transaction_date' => $params['transaction_date'],
                'posted_date' => $params['posted_date']
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 交易记录统计
     */
    public static function summary(): array
    {
        // 获取日期
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $thisMonth = date('Y-m-01');
        $lastMonth = date('Y-m-01', strtotime('-1 month'));
        $lastMonthEnd = date('Y-m-d', strtotime('-1 day', strtotime($thisMonth)));

        // 今日交易总额（绝对值）
        $todayAmount = TransactionRecord::whereDay('transaction_date', $today)
            ->sum(Db::raw('ABS(billing_amount)'));

        // 昨日交易总额
        $yesterdayAmount = TransactionRecord::whereDay('transaction_date', $yesterday)
            ->sum(Db::raw('ABS(billing_amount)'));

        // 本月交易总额
        $thisMonthAmount = TransactionRecord::whereTime('transaction_date', '>=', $thisMonth)
            ->sum(Db::raw('ABS(billing_amount)'));

        // 上月交易总额
        $lastMonthAmount = TransactionRecord::whereTime('transaction_date', 'between', [$lastMonth, $lastMonthEnd])
            ->sum(Db::raw('ABS(billing_amount)'));

        // 总交易额
        $totalAmount = TransactionRecord::sum(Db::raw('ABS(billing_amount)'));

        // 拒付交易总数（使用transaction_type='declined'作为条件）
        $declineCount = TransactionRecord::where('transaction_type', 'declined')
            ->count();
            
        // 拒付交易总金额
        $declineAmount = TransactionRecord::where('transaction_type', 'declined')
            ->sum(Db::raw('ABS(billing_amount)'));
            
        // 总交易笔数
        $totalCount = TransactionRecord::count();

        // 计算拒付率（拒付金额/总交易金额）
        $declineRate = $totalAmount > 0 ? round($declineAmount / $totalAmount, 4) : 0;

        return [
            'today' => round($todayAmount, 2),
            'lastday' => round($yesterdayAmount, 2),
            'this_month' => round($thisMonthAmount, 2),
            'last_month' => round($lastMonthAmount, 2),
            'decline_count' => $declineCount,
            'total_count' => $totalCount,
            'decline_amount' => round($declineAmount, 2),
            'total_amount' => round($totalAmount, 2),
            'decline_rate' => $declineRate,
        ];
    }


    /**
     * @notes 获取transaction详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/04/08 19:39
     */
    public static function detail($params): array
    {
        return TransactionRecord::findOrEmpty($params['id'])->toArray();
    }
}